package com.libo.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.libo.usercenter.common.BaseResponse;
// 在文件顶部添加导入语句
import com.libo.usercenter.common.ErrorCode;

import com.libo.usercenter.common.ResultUtils;
import com.libo.usercenter.exception.BusinessException;
import com.libo.usercenter.model.domain.User;
import com.libo.usercenter.model.domain.request.UserLoginRequest;
import com.libo.usercenter.model.domain.request.UserRegisterRequest;
import com.libo.usercenter.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.libo.usercenter.contant.userConstant.*;

/**
 * 用户接口
 *
 * @author libo
 */

@RestController
@RequestMapping("/user")
public class userController {


    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
//            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String userCode = userRegisterRequest.getUserCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword,userCode)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, userCode);
        return new BaseResponse<>(0, result, "ok");
    }

    @PostMapping("/login")
    //User是返回值类型，执行完userLogin方法后，会自动返回一个User类型的对象，是项目中的实体类，对应数据库中的用户表结构，路径在com/libo/usercenter/model/domain/User.java
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
//            return null;
            return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(),null,"请求参数为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
//            return null;
            return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(),null,"账号或密码不能为空");
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        if (user == null) {
//            return null;
            return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(),null,"用户不存在或密码错误");
        }
        return new BaseResponse<>(0, user, "登录成功");
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout( HttpServletRequest request) {  //返回值用Integer，而不用int，是因为Integer可以返回null，int不可以返回null
        if (request == null) {
            return null;
        }
        int i = userService.userLogout(request);
        return new BaseResponse<>(0, i, "ok");
    }


    @GetMapping("/current")
    public User getCurrent(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if(currentUser==null){
            return null;
        }
        long userId =currentUser.getId();
        //todo 校验用户是否合法
        User user = userService.getById(userId);  //通过调用 userService.getById(userId) 方法，根据用户 ID 查询完整的用户信息：
        return userService.getSafetyUser(user);
    }


    @GetMapping("/search")
    public List<User> searchUsers(String username, HttpServletRequest request) {
        //鉴权，仅管理员可查询
        if(!isAdmin(request)){
            return new ArrayList <>();
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //未使用isAdmin前
//        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
//        User user = (User) userObj;
//        if (user == null || user.getRole() != ADMIN_ROLE) {
//            return new ArrayList<>();
//        }
        QueryWrapper<User>queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
//        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());

//        return new BaseResponse<>(0, list, "ok");
//        return userList.stream().map(user -> {
//            user.setUserPassword(null);
//            return userService.getSafetyUser(user);
//        }).collect(Collectors.toList());
    }

    @PostMapping("/delete") //这里采用的是逻辑删除，即把isDelete字段设置为1
    public boolean deleteUsers(@RequestBody long id,HttpServletRequest request) {
        //鉴权，仅管理员可删除
        if(!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
//            return false;
        }
        //未使用isAdmin前
//        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
//        User user = (User) userObj;
//        if (user == null || user.getRole() != ADMIN_ROLE) {
//            return false;
//        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//            return false;
        }
        return userService.removeById(id);
    }

    /**
     * 判断当前用户是否为管理员
     * @param request
     * @return
     */
    private Boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
//        if (user == null || user.getRole()==DEFAULT_ROLE){
//            return false;
//        }
//        return true;
        //优化
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }

}
